// search.js
const MockData = require('../../utils/mockData.js')

Page({
  data: {
    searchKeyword: '',
    searchHistory: [],
    rankingList: [], // 排行榜数据
    searchResults: {
      courses: [],      // 课程结果
      acupoints: [],    // 穴位结果
      reflexZones: [],  // 反射区结果
      products: [],     // 商品结果
      techniques: []    // 技法结果
    },
    hasResults: false,
    showEmpty: false,
    // AI助手相关
    showAIChat: false,
    showAIRecommend: false,
    isAITyping: false,
    aiChatMessages: [],
    aiRecommendations: {
      personalized: [],
      lastUpdated: ''
    },
    aiKeywords: ['聊天', '个性化推荐', '穴位推荐', '技法推荐', '健康咨询']
  },

  onLoad(options) {
    console.log('搜索页面加载', options)
    this.loadSearchHistory()
    this.loadRankingList() // 加载排行榜数据
    
    // 如果传入了关键词，自动搜索
    if (options.keyword) {
      this.setData({
        searchKeyword: options.keyword
      })
      this.performSearch(options.keyword)
      this.saveSearchHistory(options.keyword)
    }
    
    // 测试：自动显示AI个性化推荐（可以删除）
    setTimeout(() => {
      console.log('测试：自动显示AI个性化推荐')
      this.startAIRecommendation()
    }, 2000)
  },

  // 加载搜索历史
  loadSearchHistory() {
    const history = wx.getStorageSync('searchHistory') || []
    this.setData({
      searchHistory: history
    })
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    if (!keyword || keyword.trim() === '') return
    
    let history = wx.getStorageSync('searchHistory') || []
    
    // 移除重复项
    history = history.filter(item => item !== keyword)
    
    // 添加到开头
    history.unshift(keyword)
    
    // 限制历史记录数量
    if (history.length > 10) {
      history = history.slice(0, 10)
    }
    
    wx.setStorageSync('searchHistory', history)
    this.setData({
      searchHistory: history
    })
  },

  // 加载排行榜数据
  loadRankingList() {
    const rankingList = [
      {
        id: 1,
        title: '热门穴位',
        icon: '📍',
        items: [
          { name: '足三里', count: 12580, type: 'acupoint' },
          { name: '合谷穴', count: 11200, type: 'acupoint' },
          { name: '百会穴', count: 9800, type: 'acupoint' },
          { name: '内关穴', count: 8900, type: 'acupoint' },
          { name: '涌泉穴', count: 7600, type: 'acupoint' }
        ]
      },
      {
        id: 2,
        title: '热门技法',
        icon: '🧘',
        items: [
          { name: '按摩', count: 15600, type: 'technique' },
          { name: '艾灸', count: 13200, type: 'technique' },
          { name: '拔罐', count: 10800, type: 'technique' },
          { name: '刮痧', count: 9200, type: 'technique' },
          { name: '推拿', count: 7800, type: 'technique' }
        ]
      },
      {
        id: 3,
        title: '热门课程',
        icon: '📚',
        items: [
          { name: '中医基础', count: 18900, type: 'course' },
          { name: '穴位养生', count: 14500, type: 'course' },
          { name: '经络调理', count: 12800, type: 'course' },
          { name: '体质调理', count: 11200, type: 'course' },
          { name: '四季养生', count: 9600, type: 'course' }
        ]
      }
    ]
    
    this.setData({
      rankingList: rankingList
    })
  },

  // 刷新排行榜
  onRefreshRanking() {
    wx.showToast({
      title: '正在刷新...',
      icon: 'loading',
      duration: 1000
    })
    
    // 模拟刷新延迟
    setTimeout(() => {
      this.loadRankingList()
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 1500
      })
    }, 1000)
  },

  // 排行榜项点击
  onRankingItemTap(e) {
    const { category, item } = e.currentTarget.dataset
    const keyword = item.name
    
    console.log('点击排行榜项:', { category, item })
    
    // 如果是热门穴位，跳转到3D展示页面
    if (category === '热门穴位') {
      wx.navigateTo({
        url: `/pages/acupoint-3d/acupoint-3d?acupoint=${encodeURIComponent(keyword)}`
      })
      return
    }
    
    // 其他分类执行搜索
    this.setData({
      searchKeyword: keyword
    })
    
    this.saveSearchHistory(keyword)
    this.performSearch(keyword)
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value
    this.setData({
      searchKeyword: keyword
    })
    
    // 如果清空输入框，重置搜索结果
    if (!keyword.trim()) {
      this.setData({
        searchResults: {
          courses: [],
          acupoints: [],
          reflexZones: [],
          products: [],
          techniques: []
        },
        hasResults: false,
        showEmpty: false
      })
    }
  },

  // 搜索按钮点击
  onSearchButtonClick() {
    const keyword = this.data.searchKeyword
    if (keyword && keyword.trim()) {
      this.saveSearchHistory(keyword)
      this.performSearch(keyword)
    } else {
      wx.showToast({
        title: '请输入搜索内容',
        icon: 'none'
      })
    }
  },

  // 搜索确认
  onSearchConfirm(e) {
    const keyword = e.detail.value
    if (keyword.trim()) {
      this.saveSearchHistory(keyword)
      this.performSearch(keyword)
    }
  },

  // 执行搜索
  performSearch(keyword) {
    console.log('搜索关键词:', keyword)
    
    const lowerKeyword = keyword.toLowerCase()
    const results = {
      courses: [],
      acupoints: [],
      reflexZones: [],
      products: [],
      techniques: []
    }
    
    // 搜索课程
    results.courses = MockData.courses.filter(item => 
      item.title.toLowerCase().includes(lowerKeyword) || 
      item.intro.toLowerCase().includes(lowerKeyword) ||
      item.typeText.toLowerCase().includes(lowerKeyword) ||
      item.detail.toLowerCase().includes(lowerKeyword) ||
      // 支持按价格类型搜索：免费、付费
      (item.isFree && '免费'.includes(keyword)) ||
      (!item.isFree && '付费'.includes(keyword))
    ).map(item => ({
      ...item,
      type: 'course'
    }))
    
    // 搜索穴位
    results.acupoints = MockData.acupoints.filter(item => 
      item.imageTitle.toLowerCase().includes(lowerKeyword) || 
      item.description.toLowerCase().includes(lowerKeyword) ||
      item.categoryText.toLowerCase().includes(lowerKeyword) ||
      item.bodyPosition.toLowerCase().includes(lowerKeyword) ||
      // 支持组合搜索：如"成人足三里"
      (item.categoryText + item.imageTitle).toLowerCase().includes(lowerKeyword)
    ).map(item => ({
      ...item,
      type: 'acupoint'
    }))
    
    // 搜索反射区
    results.reflexZones = MockData.reflexZones.filter(item => 
      item.name.toLowerCase().includes(lowerKeyword) || 
      item.function.toLowerCase().includes(lowerKeyword) ||
      item.location.toLowerCase().includes(lowerKeyword) ||
      item.positionText.toLowerCase().includes(lowerKeyword) ||
      // 支持多关键词匹配：如"足部肾脏"可以匹配到"足部"的"肾脏反射区"
      (item.positionText + item.name).toLowerCase().includes(lowerKeyword)
    ).map(item => ({
      ...item,
      type: 'reflex'
    }))
    
    // 搜索商品
    results.products = MockData.products.filter(item => 
      item.name.toLowerCase().includes(lowerKeyword) || 
      item.intro.toLowerCase().includes(lowerKeyword)
    ).map(item => ({
      ...item,
      type: 'product'
    }))
    
    // 搜索技法
    const techniques = [
      { 
        id: 'massage', 
        name: '按摩', 
        description: '中医按摩是一种古老的治疗方法，通过手法作用于人体特定部位', 
        icon: '🤲',
        type: 'massage'
      },
      { 
        id: 'moxibustion', 
        name: '艾灸', 
        description: '艾灸是用艾叶制成的艾条或艾柱点燃后熏烤人体穴位', 
        icon: '🔥',
        type: 'moxibustion'
      },
      { 
        id: 'cupping', 
        name: '拔罐', 
        description: '拔罐疗法是以罐为工具，利用负压吸附于体表', 
        icon: '🫙',
        type: 'cupping'
      },
      { 
        id: 'guasha', 
        name: '刮痧', 
        description: '刮痧是用刮痧板在人体表面反复刮动、摩擦', 
        icon: '✨',
        type: 'guasha'
      }
    ]
    
    results.techniques = techniques.filter(item => 
      item.name.toLowerCase().includes(lowerKeyword) || 
      item.description.toLowerCase().includes(lowerKeyword)
    )
    
    // 计算总结果数
    const totalCount = results.courses.length + 
                      results.acupoints.length + 
                      results.reflexZones.length + 
                      results.products.length +
                      results.techniques.length
    
    this.setData({
      searchResults: results,
      hasResults: totalCount > 0,
      showEmpty: totalCount === 0 && keyword.trim() !== ''
    })
  },

  // 标签点击
  onTagTap(e) {
    const keyword = e.currentTarget.dataset.keyword
    this.setData({
      searchKeyword: keyword
    })
    
    this.saveSearchHistory(keyword)
    this.performSearch(keyword)
  },

  // 清空搜索历史
  onClearHistory() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('searchHistory')
          this.setData({
            searchHistory: []
          })
          wx.showToast({
            title: '已清空',
            icon: 'success'
          })
        }
      }
    })
  },

  // 课程点击
  onCourseTap(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/course-detail/course-detail?id=${id}`
    })
  },

  // 穴位点击
  onAcupointTap(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/acupoint-detail/acupoint-detail?id=${id}`
    })
  },

  // 反射区点击
  onReflexTap(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/reflex-detail/reflex-detail?id=${id}`
    })
  },

  // 商品点击
  onProductTap(e) {
    const id = e.currentTarget.dataset.id
    wx.showToast({
      title: '商品详情开发中',
      icon: 'none'
    })
  },

  // 技法点击
  onTechniqueTap(e) {
    const type = e.currentTarget.dataset.type
    wx.navigateTo({
      url: `/pages/technique-detail/technique-detail?type=${type}`
    })
  },

  // 查看更多
  onViewMore(e) {
    const type = e.currentTarget.dataset.type
    const keyword = this.data.searchKeyword
    
    // 根据类型跳转到对应列表页
    switch(type) {
      case 'course':
        wx.navigateTo({
          url: `/pages/courses/courses?keyword=${keyword}`
        })
        break
      case 'acupoint':
        wx.navigateTo({
          url: `/pages/acupoints/acupoints?keyword=${keyword}`
        })
        break
      case 'reflex':
        wx.navigateTo({
          url: `/pages/reflex/reflex?keyword=${keyword}`
        })
        break
      case 'product':
        wx.switchTab({
          url: '/pages/mall/mall'
        })
        break
    }
  },

  // 返回上一页
  goBack() {
    if (getCurrentPages().length > 1) {
      wx.navigateBack()
    } else {
      wx.switchTab({ url: '/pages/index/index' })
    }
  },

  // ========== AI助手相关方法 ==========

  // AI关键词点击
  onAIKeywordTap(e) {
    const keyword = e.currentTarget.dataset.keyword
    console.log('AI关键词点击:', keyword)
    
    if (keyword === '聊天') {
      this.startAIChat()
    } else if (keyword === '个性化推荐') {
      this.startAIRecommendation()
    } else {
      // 其他关键词作为搜索，并生成智能推荐
      this.setData({ searchKeyword: keyword })
      this.performSearch(keyword)
      
      // 基于关键词生成智能推荐
      this.setData({
        showAIRecommend: true,
        showAIChat: false
      })
      this.generateSmartRecommendations(keyword)
    }
  },

  // 开始AI聊天
  startAIChat() {
    console.log('开始AI聊天')
    this.setData({
      showAIChat: true,
      showAIRecommend: false,
      aiChatMessages: [
        {
          type: 'ai',
          content: '您好！我是智疗智能助手，可以为您提供中医养生、穴位按摩、技法学习等方面的专业建议。有什么可以帮助您的吗？',
          timestamp: Date.now()
        }
      ]
    })
  },

  // 关闭AI聊天
  onCloseAIChat() {
    this.setData({
      showAIChat: false,
      aiChatMessages: []
    })
  },

  // 发送聊天消息
  onSendChatMessage() {
    const keyword = this.data.searchKeyword.trim()
    if (!keyword) return

    // 添加用户消息
    const userMessage = {
      type: 'user',
      content: keyword,
      timestamp: Date.now()
    }

    this.setData({
      aiChatMessages: [...this.data.aiChatMessages, userMessage],
      isAITyping: true,
      searchKeyword: ''
    })

    // 模拟AI回复
    setTimeout(() => {
      this.generateAIResponse(keyword)
    }, 1500)
  },

  // 生成AI回复
  generateAIResponse(userInput) {
    const responses = this.getAIResponses(userInput)
    const aiMessage = {
      type: 'ai',
      content: responses.content,
      timestamp: Date.now(),
      suggestions: responses.suggestions || []
    }

    this.setData({
      aiChatMessages: [...this.data.aiChatMessages, aiMessage],
      isAITyping: false
    })
  },

  // 获取AI回复内容
  getAIResponses(input) {
    const lowerInput = input.toLowerCase()
    
    // 穴位相关
    if (lowerInput.includes('穴位') || lowerInput.includes('按摩')) {
      return {
        content: '穴位按摩是中医的重要疗法。我为您推荐几个常用穴位：\n\n• 足三里：调理脾胃，增强免疫力\n• 合谷穴：缓解头痛，调节气血\n• 百会穴：安神定志，提升精神状态\n\n您想了解哪个穴位的具体按摩方法吗？',
        suggestions: ['足三里按摩方法', '合谷穴位置', '百会穴功效']
      }
    }
    
    // 技法相关
    if (lowerInput.includes('技法') || lowerInput.includes('推拿') || lowerInput.includes('艾灸')) {
      return {
        content: '中医技法博大精深！根据您的需求，我推荐：\n\n• 推拿：适合肌肉酸痛、疲劳\n• 艾灸：温通经络，散寒除湿\n• 拔罐：活血化瘀，祛风除湿\n• 刮痧：清热解毒，通经活络\n\n您想学习哪种技法的具体操作？',
        suggestions: ['推拿手法', '艾灸穴位', '拔罐注意事项']
      }
    }
    
    // 健康咨询
    if (lowerInput.includes('健康') || lowerInput.includes('养生') || lowerInput.includes('调理')) {
      return {
        content: '中医养生注重整体调理，建议从以下几个方面入手：\n\n• 饮食调理：清淡饮食，少食多餐\n• 作息规律：早睡早起，保证充足睡眠\n• 情志调节：保持心情愉悦，避免过度紧张\n• 适度运动：如太极拳、八段锦等\n\n您想了解哪个方面的具体建议？',
        suggestions: ['饮食养生', '作息调理', '情志调节']
      }
    }
    
    // 默认回复
    return {
      content: '感谢您的提问！作为智疗智能助手，我可以为您提供：\n\n• 穴位按摩指导\n• 中医技法学习\n• 健康养生建议\n• 个性化推荐\n\n请告诉我您具体想了解什么，我会为您提供专业的建议。',
      suggestions: ['穴位推荐', '技法学习', '健康咨询']
    }
  },

  // 点击AI建议
  onAISuggestionTap(e) {
    const suggestion = e.currentTarget.dataset.suggestion
    this.setData({ searchKeyword: suggestion })
    this.onSendChatMessage()
  },

  // 开始AI个性化推荐
  startAIRecommendation() {
    console.log('开始AI个性化推荐')
    this.setData({
      showAIRecommend: true,
      showAIChat: false
    })
    this.generateAIRecommendations()
  },

  // 基于搜索关键词的智能推荐
  generateSmartRecommendations(keyword) {
    console.log('基于关键词生成智能推荐:', keyword)
    
    // 根据关键词智能匹配推荐内容
    let smartRecommendations = []
    
    if (keyword.includes('穴位') || keyword.includes('按摩')) {
      smartRecommendations = [
        {
          id: 'smart_acupoints',
          title: '相关穴位推荐',
          icon: '📍',
          items: [
            { name: '足三里', count: '12580', type: 'acupoint', reason: '调理脾胃，增强免疫力', description: '位于小腿前外侧，犊鼻下3寸，胫骨前缘一横指处' },
            { name: '合谷穴', count: '11200', type: 'acupoint', reason: '缓解头痛，调节气血', description: '位于手背，第1、2掌骨间，当第2掌骨桡侧的中点处' },
            { name: '内关穴', count: '8900', type: 'acupoint', reason: '宁心安神，理气止痛', description: '位于前臂掌侧，当曲泽与大陵的连线上，腕横纹上2寸' }
          ]
        }
      ]
    } else if (keyword.includes('技法') || keyword.includes('推拿') || keyword.includes('艾灸')) {
      smartRecommendations = [
        {
          id: 'smart_techniques',
          title: '相关技法推荐',
          icon: '🧘',
          items: [
            { name: '推拿按摩', count: '15600', type: 'technique', reason: '疏通经络，缓解疲劳', description: '通过手法刺激穴位和经络，达到治疗和保健的目的' },
            { name: '艾灸疗法', count: '13200', type: 'technique', reason: '温通经络，散寒除湿', description: '利用艾叶燃烧产生的热力刺激穴位，温通经络' },
            { name: '穴位按压', count: '7800', type: 'technique', reason: '简单易学，效果显著', description: '用手指按压特定穴位，刺激经络，调节身体机能' }
          ]
        }
      ]
    } else if (keyword.includes('课程') || keyword.includes('学习') || keyword.includes('养生')) {
      smartRecommendations = [
        {
          id: 'smart_courses',
          title: '相关课程推荐',
          icon: '📚',
          items: [
            { name: '中医基础理论', count: '8500', type: 'course', reason: '系统学习中医理论', description: '从基础理论开始，系统学习中医知识体系' },
            { name: '穴位按摩入门', count: '7200', type: 'course', reason: '实用性强，易上手', description: '学习常用穴位的定位和按摩方法' },
            { name: '经络养生', count: '6800', type: 'course', reason: '全面了解经络系统', description: '深入学习十二经络和奇经八脉' }
          ]
        }
      ]
    } else {
      // 默认推荐
      smartRecommendations = this.data.aiRecommendations
    }
    
    this.setData({
      aiRecommendations: {
        personalized: smartRecommendations,
        lastUpdated: new Date().toLocaleString()
      },
      aiQueryKeyword: keyword
    })
  },

  // 关闭AI推荐
  onCloseAIRecommend() {
    this.setData({
      showAIRecommend: false,
      aiRecommendations: {
        personalized: [],
        lastUpdated: ''
      }
    })
  },

  // 刷新AI推荐
  onRefreshAIRecommend() {
    this.generateAIRecommendations()
  },

  // 生成AI个性化推荐
  generateAIRecommendations() {
    // 使用真实的课程和穴位数据生成推荐
    const realRecommendations = [
      {
        id: 'acupoints',
        title: '热门穴位',
        icon: '📍',
        items: [
          { name: '足三里', count: '12580', type: 'acupoint', reason: '调理脾胃，增强免疫力', description: '位于小腿前外侧，犊鼻下3寸，胫骨前缘一横指处' },
          { name: '合谷穴', count: '11200', type: 'acupoint', reason: '缓解头痛，调节气血', description: '位于手背，第1、2掌骨间，当第2掌骨桡侧的中点处' },
          { name: '百会穴', count: '9800', type: 'acupoint', reason: '安神定志，提升精神状态', description: '位于头部，当前发际正中直上5寸，或两耳尖连线中点处' },
          { name: '内关穴', count: '8900', type: 'acupoint', reason: '宁心安神，理气止痛', description: '位于前臂掌侧，当曲泽与大陵的连线上，腕横纹上2寸' },
          { name: '涌泉穴', count: '7600', type: 'acupoint', reason: '滋阴降火，宁神开窍', description: '位于足底部，蜷足时足前部凹陷处，约当足底第2、3跖趾缝纹头端与足跟连线的前1/3与后2/3交点上' }
        ]
      },
      {
        id: 'techniques',
        title: '热门技法',
        icon: '🧘',
        items: [
          { name: '推拿按摩', count: '15600', type: 'technique', reason: '疏通经络，缓解疲劳', description: '通过手法刺激穴位和经络，达到治疗和保健的目的' },
          { name: '艾灸疗法', count: '13200', type: 'technique', reason: '温通经络，散寒除湿', description: '利用艾叶燃烧产生的热力刺激穴位，温通经络' },
          { name: '拔罐疗法', count: '10800', type: 'technique', reason: '活血化瘀，祛风除湿', description: '通过负压作用，使局部组织充血，达到治疗目的' },
          { name: '刮痧疗法', count: '9200', type: 'technique', reason: '清热解毒，通经活络', description: '用刮痧板在体表反复刮动，使局部皮肤出现痧痕' },
          { name: '穴位按压', count: '7800', type: 'technique', reason: '简单易学，效果显著', description: '用手指按压特定穴位，刺激经络，调节身体机能' }
        ]
      },
      {
        id: 'courses',
        title: '推荐课程',
        icon: '📚',
        items: [
          { name: '中医基础理论', count: '8500', type: 'course', reason: '系统学习中医理论', description: '从基础理论开始，系统学习中医知识体系' },
          { name: '穴位按摩入门', count: '7200', type: 'course', reason: '实用性强，易上手', description: '学习常用穴位的定位和按摩方法' },
          { name: '经络养生', count: '6800', type: 'course', reason: '全面了解经络系统', description: '深入学习十二经络和奇经八脉' },
          { name: '四季养生', count: '5900', type: 'course', reason: '顺应自然，健康生活', description: '根据不同季节特点进行养生保健' },
          { name: '体质调理', count: '5100', type: 'course', reason: '个性化调理方案', description: '根据个人体质特点制定调理方案' }
        ]
      }
    ]

    this.setData({
      aiRecommendations: {
        personalized: realRecommendations,
        lastUpdated: new Date().toLocaleString()
      }
    })
  },

  // AI推荐项点击
  onAIRecommendTap(e) {
    const item = e.currentTarget.dataset.item
    console.log('AI推荐点击:', item)
    
    // 根据推荐类型跳转到相应页面
    if (item.type === 'acupoint') {
      wx.navigateTo({
        url: `/pages/acupoints/acupoints?keyword=${item.name}`
      })
    } else if (item.type === 'technique') {
      wx.navigateTo({
        url: `/pages/techniques/techniques?keyword=${item.name}`
      })
    } else if (item.type === 'course') {
      // 跳转到课程列表页面，搜索相关课程
      wx.navigateTo({
        url: `/pages/courses/courses?keyword=${item.name}`
      })
    }
  }
})
